package com.teach;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Arrays;


public class Socket01 {
	private static final int PORT = 1000;
	public static void main(String[] args) {
		ServerSocket  serverSocket =  null;
		try {
//			serverSocket  = new ServerSocket();
//			SocketAddress address = new InetSocketAddress(PORT);
//			address = new InetSocketAddress(InetAddress.getByName("192.168.31.112"),PORT);
//			serverSocket.bind(address);
//			
			//第二种方法
			serverSocket =new ServerSocket(PORT);
			//serverSocket =new ServerSocket(PORT,50,InetAddress.getByName("192.168.31.112"));
			
			System.out.println("服务器创建完成"+serverSocket.getInetAddress().getHostAddress()+serverSocket.getLocalPort());
			System.out.println(serverSocket.getLocalPort());
			System.out.println(serverSocket.getInetAddress());
			//接收一个客户端连接
			Socket client = serverSocket.accept();
			
			System.out.println(client.getPort());
			System.out.println(client.getInetAddress());
			System.out.println(client.getLocalPort());
			System.out.println(client.getLocalAddress());
			System.out.println(client.getRemoteSocketAddress());
			System.out.println(client.getInputStream());
			System.out.println(client.getOutputStream());
			
			///接收一段客户端发送的字节数组
			InputStream in = client.getInputStream();
			byte[] bs = new byte[10];
			int len = in.read(bs);
			System.out.println("接收一段客户端发送的字节数组"+len+"="+Arrays.toString(bs));
			
			//向客户端发送一段字节数组
			OutputStream out = client.getOutputStream();
			bs [9] = 9;
			out.write(bs);
			out.flush();
			System.out.println("向客户端发送一段字节数组");
			
			System.out.format("关闭服务器[]",client.getInetAddress().getHostAddress(),client.getPort());
			client.close();
			serverSocket.close();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		
	}
}
